#include "savebundle.h"
#include <cassert>
#include "Famicom.h"

SaveBundle::SaveBundle(Famicom *fc):famicom(fc)
{
	//mSaveData = new uint8_t[MAX_SAVE_BYTES];
}

SaveBundle::~SaveBundle()
{
	//delete[] mSaveData;
}

void SaveBundle::Reset()
{
	//memset(mSaveData, 0, MAX_SAVE_BYTES);
	//restorepos = savepos = 0;
}



void SaveBundle::ResetRestore()
{
	//this->restorepos = 0;
}
void SaveBundle::ResetSave()
{
	//this->savepos = 0;
}


void SaveBundle::SaveByte(uint8_t data)
{
	Write((char*)&data, 1);
	//if (savepos < MAX_SAVE_BYTES)
	//	this->mSaveData[savepos++] = data;
	//else
	//	assert(!"The saved data is too large!");
}


void SaveBundle::SaveWord(uint16_t data)
{
	this->SaveByte(data);
	this->SaveByte(data >> 8);
}


void SaveBundle::SavePtr(uint32_t data)
{
	this->SaveByte(data);
	this->SaveByte(data >> 8);
	this->SaveByte(data >> 16);
	this->SaveByte(data >> 24);
}


void SaveBundle::SaveBlock(uint8_t* data, size_t size)
{
	Write((char*)data, size);
	//if (savepos + size <= MAX_SAVE_BYTES)
	//{
	//	memcpy(mSaveData + savepos, data, size);
	//	savepos += size;
	//}
	//else
	//	assert(!"The saved data is too large!");
}


uint8_t SaveBundle::RestoreByte()
{
	char byte;
	Read((char*)&byte, 1);
	return byte;
	//if (restorepos < savepos)
	//{
	//	return mSaveData[restorepos++];
	//}
	//else
	//	assert(!"The recovered data is too large!");
	//return 0;
}


uint16_t SaveBundle::RestoreWord()
{
	return RestoreByte() | ((uint16_t)RestoreByte() << 8);
}


uint32_t SaveBundle::RestorePtr()
{
	return ((uint32_t)this->RestoreByte()
		| (uint32_t)this->RestoreByte() << 8
		| (uint32_t)this->RestoreByte() << 16
		| (uint32_t)this->RestoreByte() << 24);
}


void SaveBundle::RestoreBlock(uint8_t* dst, size_t size)
{
	Read((char*)dst, size);
}

bool SaveBundle::Open(bool issave)
{
	if (famicom->ifcevent != nullptr)
		return famicom->ifcevent->OnSaveBundleOpen(issave);
	return false;
}

bool SaveBundle::Close()
{
	if (famicom->ifcevent != nullptr)
		return famicom->ifcevent->OnSaveBundleClose();
	return false;
}

void SaveBundle::Write(char* buf, int size)
{
	if (famicom->ifcevent != nullptr)
		 famicom->ifcevent->OnSaveBundleWrite(buf,size);
}

void SaveBundle::Read(char* buf, int size)
{
	if (famicom->ifcevent != nullptr)
		famicom->ifcevent->OnSaveBundleRead(buf, size);
}
